package com.lty.jeeg.server.modules.fas.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.lty.jeeg.server.common.dto.ResponseInfo;
import com.lty.jeeg.server.common.exception.MyException;
import com.lty.jeeg.server.common.utils.BeanConverter;
import com.lty.jeeg.server.common.utils.ResponseUtil;
import com.lty.jeeg.server.modules.fas.dto.GoodsCategoryDTO;
import com.lty.jeeg.server.modules.fas.vo.GoodsCategoryVO;
import io.swagger.annotations.Api;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.lty.jeeg.server.modules.fas.model.GoodsCategory;
import com.lty.jeeg.server.modules.fas.service.GoodsCategoryService;

import io.swagger.annotations.ApiOperation;

import java.util.List;

/**
 * @author : LTY
 * @date : 2019-01-18 09:17:16
 * Description : 商品分类
 */
@Api(tags = "商品分类")
@RestController
@RequestMapping("/goodsCategory")
public class GoodsCategoryController {

    private final GoodsCategoryService goodsCategoryService;

    @Autowired
    public GoodsCategoryController(GoodsCategoryService goodsCategoryService) {
        this.goodsCategoryService = goodsCategoryService;
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "根据id获取")
    @RequiresPermissions("fas:goodsCategory:query")
    public ResponseInfo get(@PathVariable Long id) {
        GoodsCategoryVO categoryVO = new GoodsCategoryVO();
        categoryVO.setId(id);
        if (id == 0) {
            categoryVO.setName("root");
            return ResponseUtil.success(categoryVO);
        }

        try {
            categoryVO = BeanConverter.map(goodsCategoryService.getById(id), GoodsCategoryVO.class);
        } catch (NullPointerException e) {
            throw new MyException("无此商品分类");
        }

        return ResponseUtil.success(categoryVO);
    }

    @GetMapping("getParent/{id}")
    @ApiOperation(value = "根据id获取上级商品分类")
    @RequiresPermissions("fas:goodsCategory:query")
    public ResponseInfo getParent(@PathVariable Long id) {
        GoodsCategoryDTO categoryDTO = null;
        try {
            categoryDTO = goodsCategoryService.getParentById(id);
        } catch (NullPointerException e) {
            throw new MyException("无此商品分类");
        }
        return ResponseUtil.success(BeanConverter.map(categoryDTO, GoodsCategoryVO.class));
    }

    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除")
    @RequiresPermissions("fas:goodsCategory:del")
    public ResponseInfo delete(@PathVariable Long id) {
        return ResponseUtil.success(goodsCategoryService.delete(id));
    }

    @PutMapping
    @ApiOperation(value = "修改")
    @RequiresPermissions("fas:goodsCategory:edit")
    public ResponseInfo update(@RequestBody GoodsCategoryVO categoryVO) {
        return ResponseUtil.success(goodsCategoryService.update(BeanConverter.map(categoryVO, GoodsCategoryDTO.class)));
    }

    @PostMapping
    @ApiOperation(value = "保存")
    @RequiresPermissions("fas:goodsCategory:add")
    public ResponseInfo save(@RequestBody GoodsCategoryVO categoryVO) {
        return ResponseUtil.success(goodsCategoryService.save(BeanConverter.map(categoryVO, GoodsCategoryDTO.class)));
    }

    @GetMapping(value = {"", "list"})
    @ApiOperation(value = "商品分类列表")
    @RequiresPermissions("fas:goodsCategory:query")
    public ResponseInfo treeList() {
        List<GoodsCategoryDTO> goodsCategoryList = goodsCategoryService.treeList();
        List<GoodsCategoryDTO> list = Lists.newArrayList();
        setGoodsCategoryList(0L, goodsCategoryList, list);
        return ResponseUtil.success(BeanConverter.mapList(list, GoodsCategoryVO.class));
    }

    @GetMapping("tree")
    @ApiOperation(value = "商品分类树形列表for Ztree")
    @RequiresPermissions("fas:goodsCategory:query")
    public JSONArray permissionsAll() {
        List<GoodsCategoryDTO> goodsCategoryList = goodsCategoryService.listAll();
        JSONArray array = new JSONArray();
        setGoodsCategoryTree(0L, goodsCategoryList, array);
        return array;
    }

    /**
     * 菜单树
     * 用于ZTREE展示
     * @param pId 父级节点ID
     * @param goodsCategoryList 所有商品分类列表
     * @param array 树结构array
     */
    private void setGoodsCategoryTree(Long pId, List<GoodsCategoryDTO> goodsCategoryList, JSONArray array) {
        for (GoodsCategoryDTO goodsCategory : goodsCategoryList) {
            if (goodsCategory.getParentId().equals(pId)) {
                String string = JSONObject.toJSONString(goodsCategory);
                JSONObject parent = (JSONObject) JSONObject.parse(string);
                array.add(parent);

                if (goodsCategoryList.stream().filter(p -> p.getParentId().equals(goodsCategory.getId())).findAny() != null) {
                    JSONArray child = new JSONArray();
                    parent.put("child", child);
                    setGoodsCategoryTree(goodsCategory.getId(), goodsCategoryList, child);
                }
            }
        }
    }

    /**
     * 商品分类列表
     * 用于list页面展示
     * @param dId
     * @param goodsCategoryList
     * @param list
     */
    private void setGoodsCategoryList(Long dId, List<GoodsCategoryDTO> goodsCategoryList, List<GoodsCategoryDTO> list) {
        for (GoodsCategoryDTO dto : goodsCategoryList) {
            if (dto.getParentId().equals(dId)) {
                list.add(dto);
                if (goodsCategoryList.stream().filter(p -> p.getParentId().equals(dto.getId())).findAny() != null) {
                    setGoodsCategoryList(dto.getId(), goodsCategoryList, list);
                }
            }
        }
    }

}
